<?php
namespace app\common\library\helper;

use app\common\exception\NException;
use app\common\library\Auth;
use fast\Random;
use think\Config;
use think\Request;

/**
 * Class UploadController
 * @package app\admin\controller
 * @desc 上传类
 */

class UploadHelper{

    Const COMPRESS_TRUE  = true;        //是否压缩：是
    Const COMPRESS_FALSE = false;       //是否压缩：否

    /**
     * @param $data
     * @return string
     * @throws NException
     * @throws \Exception
     */
    public static function imageUpload( $data ){

        try{

            $name         = Helper::getValue( $data, 'name', 'file' );       //文件名
            $user_id      = Helper::getValue( $data, 'user_id' );            //上传的用户id
            $admin_id     = Helper::getValue( $data, 'admin_id' );           //上传的管理员id
            $thumb_width  = Helper::getValue( $data, 'thumb_width' );        //压缩宽度
            $thumb_height = Helper::getValue( $data, 'thumb_height' );       //压缩高度

            $file = Request::instance()->file( $name );

            if (empty($file)) {
                throw new NException( __('No file upload or server upload limit exceeded') );
            }

            //判断是否已经存在附件
            $sha1 = $file->hash();

            $upload = Config::get( 'upload' );

            preg_match('/(\d+)(\w+)/', $upload['maxsize'], $matches);
            $type = strtolower($matches[2]);
            $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
            $size = (int)$upload['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);
            $fileInfo = $file->getInfo();
            $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
            $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';

            $mimetypeArr = explode(',', strtolower($upload['mimetype']));
            $typeArr = explode('/', $fileInfo['type']);

            //禁止上传PHP和HTML文件
            if (in_array($fileInfo['type'], ['text/x-php', 'text/html']) || in_array($suffix, ['php', 'html', 'htm'])) {
                throw new NException(__('Uploaded file format is limited'));
            }
            //验证文件后缀
            if ($upload['mimetype'] !== '*' &&
                (
                    !in_array($suffix, $mimetypeArr)
                    || (stripos($typeArr[0] . '/', $upload['mimetype']) !== false && (!in_array($fileInfo['type'], $mimetypeArr) && !in_array($typeArr[0] . '/*', $mimetypeArr)))
                )
            ) {
                throw new NException(__('Uploaded file format is limited'));
            }
            //验证是否为图片文件
            $imagewidth = $imageheight = 0;
            if (in_array($fileInfo['type'], ['image/gif', 'image/jpg', 'image/jpeg', 'image/bmp', 'image/png', 'image/webp']) || in_array($suffix, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'webp'])) {
                $imgInfo = getimagesize($fileInfo['tmp_name']);
                if (!$imgInfo || !isset($imgInfo[0]) || !isset($imgInfo[1])) {
                    throw new NException(__('Uploaded file is not a valid image'));
                }
                $imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
                $imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
            }
            $replaceArr = [
                '{year}'     => date("Y"),
                '{mon}'      => date("m"),
                '{day}'      => date("d"),
                '{hour}'     => date("H"),
                '{min}'      => date("i"),
                '{sec}'      => date("s"),
                '{random}'   => Random::alnum(16),
                '{random32}' => Random::alnum(32),
                '{filename}' => $suffix ? substr($fileInfo['name'], 0, strripos($fileInfo['name'], '.')) : $fileInfo['name'],
                '{suffix}'   => $suffix,
                '{.suffix}'  => $suffix ? '.' . $suffix : '',
                '{filemd5}'  => md5_file($fileInfo['tmp_name']),
            ];
            $savekey = $upload['savekey'];
            $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);

            $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
            $fileName = substr($savekey, strripos($savekey, '/') + 1);

            $splInfo = $file->validate(['size' => $size])->move(ROOT_PATH . '/public' . $uploadDir, $fileName);

            if( ! $splInfo ){
                throw new NException( '上传失败' );
            }

            //图片压缩
            if( is_file( $splInfo->getPathname() ) ){

                if( $thumb_width && $thumb_height ){

                    ImageHelper::thumb( $splInfo->getPathname(), $thumb_width, $thumb_height );

                }

            }

            $params = array(
                'admin_id'    => $admin_id,
                'user_id'     => $user_id,
                'filesize'    => $fileInfo['size'],
                'imagewidth'  => $imagewidth,
                'imageheight' => $imageheight,
                'imagetype'   => $suffix,
                'imageframes' => 0,
                'mimetype'    => $fileInfo['type'],
                'url'         => $uploadDir . $splInfo->getSaveName(),
                'uploadtime'  => time(),
                'storage'     => 'local',
                'sha1'        => $sha1,
            );
            $attachment = model("attachment");
            $attachment->data(array_filter($params));
            $attachment->save();
            \think\Hook::listen("upload_after", $attachment);

            return $uploadDir . $splInfo->getSaveName();


        }catch( NException $e ){
            throw new NException( $e->getMessage() );
        }catch( \Exception $e ){
            Helper::logError( $e );
            throw new \Exception();
        }

    }

    /**
     * @param string $name
     * @param $is_compress       //是否生成缩略图
     * @return array
     * @throws NException
     */
    public static function imageUpload_1( $name = 'file', $is_compress = self::COMPRESS_FALSE ){

        //针对webUpload的上传
        if( is_array( $name ) ){

            $position_data = json_decode( $name[ 'avatar_data' ], true );
            $name          = 'avatar_file';

        }

        $file = request()->file( $name );

        //图片上传
        $res_upload = self::_imageArrUpload( $file );

        //如果是webUpload图片需要裁剪的话
        if( isset( $position_data ) ){

            foreach( $res_upload as $key => &$val ){

                ImageHelper::crop(
                    $val[ 'path_real' ],
                    $position_data[ 'width' ],
                    $position_data[ 'height' ],
                    $position_data[ 'x' ],
                    $position_data[ 'y' ]
                );

            }

            unset( $val );

        }

        $res = [];

        //图片缩略
        if( $is_compress ){

            foreach( $res_upload as $key => $val ){

                //150 * 150
                $path_150_150 = ImageHelper::thumb( $val[ 'path_real' ], 150, 150, true );

                //550 * 550
                $path_550_550 = ImageHelper::thumb( $val[ 'path_real' ], 550, 550, true );

                $res[] = [
                    'path'         => $val[ 'path' ],
                    'path_150_150' => $path_150_150[ 'filename_relative' ],
                    'path_550_550' => $path_550_550[ 'filename_relative' ]
                ];

            }

            $res = Helper::filterSlash( $res );

        }else{

            foreach( $res_upload as $key => $val ){

                $res[] = [
                    'path' => $val[ 'path' ],
                ];

            }

        }

        return $res;

    }

    /**
     * @desc 图片上传（多图支持）
     * @param $file
     * @return array
     * @throws NException
     */
    private static function _imageArrUpload( $file ){

        $res = [];

        if( is_array( $file ) ){

            foreach( $file as $key => $val ){

                $res[] = self::_imageUpload( $val );

            }

        }else{

            $res[] = self::_imageUpload( $file );

        }

        return $res;

    }

    /**
     * @param \think\File $file
     * @return array
     * @throws NException
     */
    private static function _imageUpload( $file ){

        if( ! $file ){
            throw new NException( '缺少上传文件' );
        }

        $folder_path      = DS . 'uploads';
        $folder_path_real = 'public' . DS . 'uploads';

        $info = $file
            ->validate( [ 'size' => 1024 * 1000 * 4, 'ext' => 'jpg,png,jpeg' ] )
            ->move( ROOT_PATH . $folder_path_real );

        if( ! $info ){
            throw new NException( '上传文件大小最大4M，后缀为jpg，png，jpeg' );
        }

        $path_real              = $info->getRealPath();
        $path_real_folder       = substr( $path_real, 0, strrpos( $path_real, DS ) );
        $path                   = $folder_path . DS . $info->getSaveName();
        $path_folder            = substr( $path, 0, strrpos( $path, DS ) );
        $filename_full          = $info->getFilename();
        $filename               = substr( $filename_full, 0, strpos( $filename_full, '.' ) );
        $file_ext               = $info->getExtension();

        $res = [
            'path_real'         => $path_real,
            'path_real_folder'  => $path_real_folder,
            'path'              => $path,
            'path_folder'       => $path_folder,
            'filename_full'     => $filename_full,
            'filename'          => $filename,
            'file_ext'          => $file_ext
        ];

        return $res;

    }

    /**
     * @param string $name
     * @return array
     * @throws \Exception
     * @desc 文件上传
     */
    public static function fileUpload( $name = 'file' ){

        try{

            $file = request()->file( $name );

            if( ! $file ){
                throw new NException( '缺少上传文件' );
            }

            $folder_path      = DS . 'uploads';
            $folder_path_real = 'public' . DS . 'uploads';

            $info = $file
                ->validate( [ 'size' => 1024 * 1000 * 40, 'ext' => 'pdf,zip,doc,docx,txt' ] )
                ->move( ROOT_PATH . $folder_path_real );

            if( ! $info ){
                throw new NException( '附件大小最大40M，后缀为pdf,zip,doc,docs,txt' );
            }

            $path_real              = $info->getRealPath();
            $path_real_folder       = substr( $path_real, 0, strrpos( $path_real, DS ) );
            $path                   = $folder_path . DS . $info->getSaveName();
            $path_folder            = substr( $path, 0, strrpos( $path, DS ) );
            $filename_full          = $info->getFilename();
            $filename               = substr( $filename_full, 0, strpos( $filename_full, '.' ) );
            $file_ext               = $info->getExtension();

            $res = [
                'path_real'         => $path_real,
                'path_real_folder'  => $path_real_folder,
                'path'              => $path,
                'path_folder'       => $path_folder,
                'filename_full'     => $filename_full,
                'filename'          => $filename,
                'file_ext'          => $file_ext
            ];

            $res = Helper::filterSlash( $res );

            return $res;

        }catch( NException $e ){
            throw new NException( $e->getMessage() );
        }catch( \Exception $e ){
            Helper::logError( $e );
            throw new \Exception();
        }

    }



}